import json
from datetime import datetime
from sqlalchemy import and_
from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import jwt_required
from app.common.commonMessage import CommonMassages
from app.service.UserPortraitService import UserPortraitService
from app.service.capitalRiskService import CapitalRiskService
from app.model.CalculationModel import CalcuResult
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

app = Flask(__name__)
# 创建蓝图
capital_risk_up = Blueprint('capital_risk_controller', __name__,url_prefix='/kshx')
# 调用服务
capitalRiskService = CapitalRiskService()
user_portrait = UserPortraitService()
# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

# 获取客商画像页面-TAB-资金风险
@capital_risk_up.route('/capital-risk', methods=['GET'])
# @jwt_required()
def get_capital_risk():
    company = request.args.get('company')
    year = request.args.get('year')
    qylx = request.args.get('is_cydw')
    # start_date = request.args.get('start_date')
    # end_date = request.args.get('end_date')
    # if start_date and end_date:
    #     start_date = datetime.strptime(start_date, '%Y-%m-%d')
    #     end_date = datetime.strptime(end_date, '%Y-%m-%d')
    # else:
    #     start_date = ''
    #     end_date = ''
    if year:
        year = int(year)
    else:
        year = datetime.now().year
    if company is not None:
        if int(qylx) in [2, 3]:
            result = session.query(CalcuResult.JSONDATA).filter(
                and_(
                    CalcuResult.GSMC == company,
                    CalcuResult.TYPE == 'cl',
                    CalcuResult.JYND == year
                )
            ).scalar()
            risk_list = json.loads(result)
        else:
        # 风险总计-其中risk_total为总和，details_total为每个风险类型的总和
            risk_list = capitalRiskService.select_capital_risk(session, company, year, int(qylx))

        if risk_list is not None:
            result = {
                "code": 200,
                "data": risk_list,
                "message": CommonMassages.CCD_SELECT_SUCCESS.value
            }
        else:
            result = {
                "code": 400,
                "data": None,
                "message": CommonMassages.CCD_SELECT_FAILED.value
            }
    else:
        result = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(result, ensure_ascii=False, cls=CustomJSONEncoder)
    # print(resp_data)
    # return Response(resp_data, content_type='application/json')
    return Response(resp_data)